package com.sgs.carbon.starter.security.core.handler;

import com.sgs.carbon.common.exception.enums.GlobalErrorCodeConstants;
import com.sgs.carbon.common.pojo.CommonResult;
import com.sgs.carbon.common.util.servlet.ServletUtils;
import com.sgs.carbon.starter.security.core.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.ExceptionTranslationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问一个需要认证的 URL 资源</br>
 * <p>已经认证（登录）但是没有权限的情况下, 返回 {@link GlobalErrorCodeConstants#FORBIDDEN} 错误码</p></br>
 * <pr>Spring Security 通过 {@link ExceptionTranslationFilter#handleAccessDeniedException(HttpServletRequest, HttpServletResponse, FilterChain, AccessDeniedException)} 方法调用当前类</pr>
 *
 * @author Dave Liu
 * @date 2021-10-02
 */
@Slf4j
@SuppressWarnings("JavadocReference")
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
            throws IOException, ServletException {
        // 打印 warn 的原因是, 不定期合并 warn, 看看有没恶意破坏
        log.warn("[commence][访问 URL({}) 时，用户({}) 权限不够]", request.getRequestURI(),
                SecurityUtils.getLoginUserId(), e);
        // 返回 403
        ServletUtils.writeJSON(response, CommonResult.error(GlobalErrorCodeConstants.UNAUTHORIZED));
    }

}
